package com.mz.ozy.activity.me;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mz.ozy.R;
import com.mz.ozy.adapter.MyOrderListAdapter;
import com.mz.ozy.base.BaseFragment;
import com.mz.ozy.bean.AssetsBean;
import com.mz.ozy.bean.EventBean;
import com.mz.ozy.bean.MyOrderBean;
import com.mz.ozy.bean.NetBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.MyOrderPresenter;
import com.mz.ozy.mvp.view.MyOrderContract;
import com.mz.ozy.utils.PayManager;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.widget.dialog.BaseDialog;
import com.mz.ozy.widget.dialog.ConfirmPayDialog;
import com.mz.ozy.widget.dialog.PayPassDialog;
import com.mz.ozy.widget.dialog.PayPassView;
import com.mz.ozy.widget.dialog.PaySelectDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/11/22.
 */
public class MyOrderFragment extends BaseFragment<MyOrderContract.View, MyOrderPresenter> implements MyOrderContract.View {

    public static final int TYPE_ALL = 10;
    public static final int TYPE_PAY = 11;
    public static final int TYPE_SEND = 12;
    public static final int TYPE_RECEIVE = 13;
    public static final int TYPE_REFUND = 14;

    @BindView(R.id.rv_content)
    RecyclerView mRvContent;
    @BindView(R.id.srl_refresh)
    SmartRefreshLayout mSrlRefresh;
    @BindView(R.id.fl_view_empty)
    FrameLayout mFlViewEmpty;
    Unbinder unbinder;
    @BindView(R.id.iv_not_data)
    ImageView ivNotData;
    private int mType;
    private int mPosition;
    private MyOrderListAdapter mAdapter;
    private String ktbalance;
    private String xfbalance;
    private MyOrderBean dataItem;
    private PayManager mPayManager;
    private int payType;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    boolean isCountDown = countDownTime();
                    if (isCountDown) {
                        mAdapter.notifyDataSetChanged();
                        handler.sendEmptyMessageDelayed(1, 1000);
                    } else {
                        mPresenter.initData(getActivity(), mType, false);
                    }
                    break;

            }
        }
    };
    private long countDownSecTime;

    public static MyOrderFragment newInstance(int type, int position) {
        Bundle args = new Bundle();
        args.putInt("type", type);
        args.putInt("position", position);
        MyOrderFragment fragment = new MyOrderFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_order, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        mType = getArguments().getInt("type");
        mPosition = getArguments().getInt("position");
        mPayManager = new PayManager(mActivity);
        init();
        ivNotData.setImageResource(R.mipmap.no_goods_icon);
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (mPresenter != null) {
                if (mPosition == MyOrderActivity.mOrderPosition) {
                    mPresenter.initData(getActivity(), mType, true);
                } else {
                    mPresenter.initData(getActivity(), mType, false);
                }
            }
        }
    }

    @Override
    public void onLoadMoreDataSuccess(MyOrderBean myOrderBean) {
        mSrlRefresh.finishLoadmore();
        mPageItemsBeans.addAll(myOrderBean.getPage().getPageItems());
        boolean isCountDown = setCountDownTime(myOrderBean.getPage().getPageItems(), myOrderBean.getDate());
        mAdapter.notifyDataSetChanged();
        handler.removeMessages(1);
        if (isCountDown) {
            handler.sendEmptyMessageDelayed(1, 1000);
        }

    }

    @Override
    public void onInitSuccess(MyOrderBean myOrderBean) {
        dataItem = myOrderBean;
        mSrlRefresh.setLoadmoreFinished(false);
        mSrlRefresh.finishRefresh();
        mPageItemsBeans.clear();
        if (myOrderBean.getPage().getPageItems().size() == 0) {
            mFlViewEmpty.setVisibility(View.VISIBLE);
        } else {
            mFlViewEmpty.setVisibility(View.GONE);
        }
        mPageItemsBeans.addAll(myOrderBean.getPage().getPageItems());
        boolean isCountDown = setCountDownTime(myOrderBean.getPage().getPageItems(), myOrderBean.getDate());
        mAdapter.notifyDataSetChanged();
        handler.removeMessages(1);
        if (isCountDown) {
            handler.sendEmptyMessageDelayed(1, 1000);
        }
    }

    private boolean setCountDownTime(List<MyOrderBean.OrderBean.PageItemsBean> pageItems, String data) {
        boolean isCountDown = false;
        if (pageItems.size() > 0) {
            for (MyOrderBean.OrderBean.PageItemsBean pageItemBean : pageItems) {
                if (pageItemBean.getState() == 0) {
                    if (startCountDown(pageItemBean, data)) {
                        isCountDown = true;
                    }
                }

            }
        }
        return isCountDown;
    }

    private boolean countDownTime() {
        boolean isCountDown = false;
        boolean reStart = false;
        if (dataItem.getPage().getPageItems().size() > 0) {
            for (MyOrderBean.OrderBean.PageItemsBean pageItemBean : dataItem.getPage().getPageItems()) {
                if (pageItemBean.getState() == 0) {
                    pageItemBean.setSpaceTime(pageItemBean.getSpaceTime() - 1);
                    if (pageItemBean.getSpaceTime() > 0) {
                        isCountDown = true;
                    } else {
                        pageItemBean.setTimeOut(true);
                        reStart = true;
                    }
                }
            }
        }
        if (reStart) {
            isCountDown = false;
        }
        return isCountDown;
    }

    private boolean startCountDown(MyOrderBean.OrderBean.PageItemsBean pageItemBean, String created) {
        try {
            String compareDate = pageItemBean.getEndtime();
            final long nowInt = Utils.parseDateIntTime(created);
            final long endtimeInt = Utils.parseDateIntTime(compareDate);

            if (endtimeInt > nowInt) {
                final long spaceTimeInt = (endtimeInt - nowInt) / 1000;
                pageItemBean.setSpaceTime(spaceTimeInt);
                return true;
            } else {
                pageItemBean.setTimeOut(true);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void onInitError(String msg) {
        this.onEmpty();
    }

    @Override
    public void onLoadMoreDataError(String msg) {
        mSrlRefresh.finishLoadmore();
    }

    @Override
    public void onLoadDataEnd() {
        mSrlRefresh.setLoadmoreFinished(true);
        mSrlRefresh.finishLoadmore();
    }

    @Override
    public void onEmpty() {
        mFlViewEmpty.setVisibility(View.VISIBLE);
//        mSrlRefresh.setEnableLoadmore(false);
    }

    @Override
    public void onConfirmSuccess(NetBean netBean) {
        mPresenter.initData(getActivity(), mType, false);
        ToastUtils.showToast("确认收货成功");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mPresenter != null) {
            if (mPosition == MyOrderActivity.mOrderPosition) {
                mPresenter.initData(getActivity(), mType, true);
            } else {
                mPresenter.initData(getActivity(), mType, false);
            }
        }
    }

    @Override
    public void onConfirmError(String msg) {

    }

    @Override
    public void onCancelOrderSuccess(NetBean netBean) {
        mPresenter.initData(getActivity(), mType, false);
        ToastUtils.showToast("取消订单成功");
    }

    @Override
    public void onCancelOrderError(String msg) {

    }

    @Override
    public void onDelOrderSuccess(NetBean netBean) {
        mPresenter.initData(getActivity(), mType, false);
        ToastUtils.showToast("删除订单成功");
    }

    @Override
    public void onDelOrderError(String msg) {

    }

    @Override
    public void geAssetsInfoSuccess(AssetsBean bean) {
        ktbalance = bean.getKtbalance();
        xfbalance = bean.getXfbalance();
    }

    @Override
    public void onPaySuccess(JSONObject orderBean) {

        if (payType == 0) { //余额支付
            ToastUtils.showToast("支付成功");
        } else if (payType == 2) {  //微信支付
            mPayManager.handleWxPay(orderBean);
        } else if (payType == 1) {  //支付宝支付
            mPayManager.handleAliPay(orderBean.optString("zfb"));
        }
        mSrlRefresh.autoRefresh();
    }

    @Override
    public void onPayError(String s) {
        ToastUtils.showToast("支付失败");
    }

    private void init() {
//        mPbLoading.setVisibility(View.VISIBLE);
        this.onEmpty();
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String data1 = dateFormat.format(date);

        mAdapter = new MyOrderListAdapter(mPageItemsBeans, data1);
        mRvContent.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvContent.setAdapter(mAdapter);
        mRvContent.setFocusableInTouchMode(false);
        mRvContent.setFocusable(false);
        mRvContent.setHasFixedSize(true);

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                final MyOrderBean.OrderBean.PageItemsBean bean = (MyOrderBean.OrderBean.PageItemsBean) adapter.getData().get(position);
                if (bean == null) return;
                switch (view.getId()) {
                    case R.id.btn_rerurn:
                        //   ReturnGoodsDetailsActivity.start(getActivity(), bean.getPrice(), bean.getNum() + "", bean.getId() + "", 1, Constants.TransCode.TransCode10038);
                        break;
                    case R.id.ll_item_view:
                    case R.id.rl_rv_parent:
                        MyOrderInfoActivity.start(getContext(), bean.getTesq(), String.valueOf(bean.getId()), bean.getState(), dataItem.getUser_balance(), bean.getType(), 0);
                        break;
                    case R.id.btn_pinl:
                        EvaluateActivity.go(getActivity(), bean.getProdcut_list(), bean.getTesq(), 0);
                        // EvaluateMainActivity.go(getActivity(), bean.getProdcut_list(), bean.getTesq());
                        break;
                    case R.id.btn_cancel: {
                        //取消订单
                        final BaseDialog dialog = new BaseDialog(getActivity(), R.layout.dialog_normal, Gravity.CENTER, true);
                        ((TextView) dialog.getView(R.id.tv_dialog_content)).setText("确认取消订单?");
                        dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.toggleDialog();
                            }
                        });
                        dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPresenter.cancelOrder(getActivity(), String.valueOf(bean.getTesq()));
                                dialog.toggleDialog();
                            }
                        });
                        dialog.toggleDialog();
                        break;
                    }
                    case R.id.btn_confirm: {//确认收货
                        final BaseDialog dialog = new BaseDialog(getActivity(), R.layout.dialog_normal, Gravity.CENTER, true);
                        ((TextView) dialog.getView(R.id.tv_dialog_content)).setText("请确认您已收到商品");
                        ((TextView) dialog.getView(R.id.tv_dialog_title)).setText("确认收货");
                        dialog.getView(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.toggleDialog();
                            }
                        });

                        dialog.getView(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPresenter.confirm(getActivity(), bean.getTesq());
                                dialog.toggleDialog();
                            }
                        });
                        dialog.toggleDialog();

                        break;
                    }
                    case R.id.btn_pay://支付
                        //               showSportsHarmDialog(bean.getId(), mAdapter.getPrice(bean), mAdapter.getPriceType(bean));

                        showPaySelectDialog(bean);


                        //   OrderPayActivity.start(getContext(), bean.getTesq());
                        break;
                    case R.id.btn_evaluate://查看详情
                        //ReturnGoodsListActivity.start(getActivity());
                        //OrderLogisticsInfoActivity.start(getContext(), bean.getTesq());
                        MyOrderInfoActivity.start(getContext(), bean.getTesq(), String.valueOf(bean.getId()), bean.getState(), dataItem.getUser_balance(), bean.getType(), 0);

                        break;
                    case R.id.btn_logistics://查看物流
                        String mAddress="";

                        Intent  _LogisticsActivity=new Intent(getActivity(), LogisticsActivity.class);
                        _LogisticsActivity.putExtra("address",mAddress);
                        _LogisticsActivity.putExtra("order",bean.getTesq());
                        startActivity(_LogisticsActivity);
                        break;
                }
            }
        });

        mSrlRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.initData(getActivity(), mType, false);
            }
        }).setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mPresenter.loadMoreData(getActivity());
            }
        });

//        getTestData();
        mFlViewEmpty.setVisibility(View.GONE);
//        mPresenter.initData(getActivity(), mType, true);
        // mPresenter.geAssetsInfo(getActivity());
    }

    private void showSportsHarmDialog(final int id, String price, int priceType) {
        ConfirmPayDialog mSportsHarmDialog = new ConfirmPayDialog(getActivity());
        mSportsHarmDialog.setBalance(ktbalance, xfbalance, price, priceType);
        mSportsHarmDialog.setOnDialogListener(new ConfirmPayDialog.onDialogListener() {
            @Override
            public void onSubmit(String msg) {
                submitPayOrder(id, msg);
                mSportsHarmDialog.toggleDialog();
            }

            @Override
            public void onCancel() {
//                    ToastUtils.showToast("取消");
                mSportsHarmDialog.toggleDialog();
            }
        });
        mSportsHarmDialog.toggleDialog();
    }

    private void submitPayOrder(int id, String msg) {
        // mPresenter.onPay(getActivity(), String.valueOf(id), msg, type, data.getType());
    }

    /**
     * 支付选择弹窗
     *
     * @param
     */
    private void showPaySelectDialog(MyOrderBean.OrderBean.PageItemsBean data) {

        if (data.getType() == 1) {
            final PayPassDialog dialog = new PayPassDialog(mActivity);
      /*  dialog.getPayViewPass().setForgetText(m);
        dialog.getPayViewPass().setYeText(balace1);*/
            dialog.getPayViewPass().setGone();
            dialog.getPayViewPass()
                    .setPayClickListener(new PayPassView.OnPayClickListener() {
                        @Override
                        public void onPassFinish(String passContent) {
                            mPresenter.onPay(getActivity(), String.valueOf(data.getId()), passContent, 0, data.getType());
                            dialog.dismiss();
                        }

                        @Override
                        public void onPayClose() {
                            dialog.dismiss();
                            //关闭回调
                        }

                        @Override
                        public void onPayForget() {
                            dialog.dismiss();
                            //点击忘记密码回调
//                        mContext.startActivity(new Intent(mContext, PayPwdActivity.class));
                            EventBus.getDefault().post(new EventBean(Constants.EventCode.JUMP_PAY_PWD, null));

                        }
                    });

        } else {
            PaySelectDialog dialog = new PaySelectDialog(getActivity(), 0);
            dialog.setOnDialogListener(new PaySelectDialog.onDialogListener() {
                @Override
                public void onConfirm(int type, String payPwd) {
                    payType = type;
                    mPresenter.onPay(getActivity(), String.valueOf(data.getId()), payPwd, type, data.getType());
                }

                @Override
                public void onCancel() {

                }
            });
//        dialog.setData(mList.get(lastPosition).getAmt()+"","");
            dialog.setData(getPrice(data), dataItem.getUser_balance() + "");
            dialog.toggleDialog();
        }

    }

    private List<MyOrderBean.OrderBean.PageItemsBean> mPageItemsBeans = new ArrayList<>();

    @NotNull
    private String getPrice(MyOrderBean.OrderBean.PageItemsBean item) {
        String price = "";
        if (!TextUtils.isEmpty(item.getActual_price()) && Double.parseDouble(item.getActual_price()) != 0.00) {

            price += "";
            price += item.getActual_price();
        }
        if (!TextUtils.isEmpty(item.getMarket_price()) && Double.parseDouble(item.getMarket_price()) != 0.00) {
            if (!TextUtils.isEmpty(price)) {
                price += "+";
                price += item.getMarket_price();
                price += "积分";
            } else {
                price += item.getMarket_price();
                price += "积分";
            }
        }
        if (TextUtils.isEmpty(price)) {
            price = "0.00";
        }
        return price;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        handler.removeMessages(1);
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBean event) {
        //刷新购物车
        if ((event.getCode() == Constants.EventCode.WX_PAY_SUCCESS || event.getCode() == Constants.EventCode.ALIPAY_PAY_SUCCESS)
                && PayManager.pay_from == 3) {
            if (mPresenter != null) {
                mPresenter.initData(getActivity(), mType, false);
            }
        }
        if ((event.getCode() == Constants.EventCode.JUMP_PAY_PWD)) {
            startActivity(new Intent(getActivity(), PayPwdActivity.class));
        }
    }
}
